package com.itheima.reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.IAdressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/addressBook")
public class AdressBookController {
    @Autowired
    private IAdressBookService adressBookService;

    //新增地址
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        adressBookService.save(addressBook);
        return R.success(addressBook);
    }

    //设置默认地址
    @PutMapping("/default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook){
        //条件构建器
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();        //过滤条件，对比id
        wrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        //设置默认条件，defalt，0
        wrapper.set(AddressBook::getIsDefault,0);
        //执行修改方法
        adressBookService.update(wrapper);
        //设置默认地址
        addressBook.setIsDefault(1);
        //执行修改方法
        adressBookService.updateById(addressBook);
        //返回结果
        return R.success(addressBook);
    }

    //根据查询id查询地址
    @GetMapping("/{id}")
    public R<AddressBook> get(@PathVariable Long id){
        AddressBook addressBook = adressBookService.getById(id);
        if (addressBook!=null){
            return R.success(addressBook);
        }else {
            return R.error("没有找到该地址");
        }
    }

    //根据id查询默认地址
    @GetMapping("/default")
    public R<AddressBook> getDefault(){
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        queryWrapper.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = adressBookService.getOne(queryWrapper);
        if (addressBook!=null){
            return R.success(addressBook);
        }else {
            return R.error("未查询到默认地址");
        }
    }
    //查询指定用户全部地址
    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook){
       addressBook.setUserId(BaseContext.getCurrentId());
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(addressBook.getUserId()!=null,AddressBook::getUserId,addressBook.getUserId());
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> list = adressBookService.list(queryWrapper);
        return R.success(list);
    }


}